package cn.youframe.frame.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * User: Administrator
 * DateTime: 12-4-25: 下午3:30
 */
public class SpringContext implements ApplicationContextAware {
    private static ApplicationContext context = null;
    private static AnnotationConfigApplicationContext ctx = null;
    /**
     * setApplicationContext
     *
     * @param applicationContext ApplicationContext
     * @throws org.springframework.beans.BeansException
     * @todo Implement this
     *   org.springframework.context.ApplicationContextAware method
     */
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    public static Object getBean(String name) {
        return context.getBean(name);
    }

    public static <T> T getBean(String name, Class<T> requiredType) {
        return context.getBean(name, requiredType);
    }

    public static Object getAnnotationBean(String name) {
        if(getCtx()){
            return ctx.getBean(name);
        }
        return null;
    }

    public static <T> T getAnnotationBean(String name, Class<T> requiredType) {
        if(getCtx()){
            return ctx.getBean(name, requiredType);
        }
        return null;
    }

    public static <T> T getAnnotationBean(Class<T> requiredType) {
        if(getCtx()){
            return ctx.getBean(requiredType);
        }
        return null;
    }

    private static boolean getCtx() {
        if (ctx == null) {
            try {
                ctx = new AnnotationConfigApplicationContext("cn.youframe");
                ctx.refresh();
            } catch (IllegalStateException ex) {
                return false;
            } catch (BeansException ex) {
                return false;
            }
        }
        return true;
    }
}
